<template>
	<el-dialog v-model="dialogFormVisible" title="审核确认" width="700" :close-on-click-modal="false" :show-close="false">
		<HyForm ref="hyFormRef" :hyFormDefault="hyFormDefault" :hyFormConfig="hyFormConfig" :hyFormFields="hyFormFields" />
    <div>
      <p style="margin-bottom:10px;font-weight:bold;">附件上传：</p>
      <el-upload
        v-model:file-list="fileList"
        class="upload-demo"
        :action="baseURL + '/admin/sys-file/upload'"
        multiple
        :before-upload="beforeUpload"
        :limit="3"
        :accept="accept"				
				:on-exceed="(files:FileList,uploadFiles:UploadFiles)=>handleExceed(files,uploadFiles,3)"
        :headers="headers"
      >
        <el-button type="primary" icon="Upload">上传附件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            仅支持上传{{accept}}格式文件，文件不能超过200MB
          </div>
        </template>
      </el-upload>
    </div>
    <template #footer>
			<div class="dialog-footer">
				<el-button @click="handleCancel">取消</el-button>
				<el-button type="primary" @click="confirm" :loading="loading">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>
<script lang="ts">
import { defineComponent,computed,toRaw } from 'vue';
import HyForm from '/@/components/HyForm/index.vue';
import Upload from '/@/components/Upload/index.vue';
import { Session } from '/@/utils/storage';
import { ElMessage } from 'element-plus';
import { appDeclareApprove } from '/@/api/areaDigital'
import type { UploadUserFile,UploadFiles } from 'element-plus';
export default defineComponent({
	name: 'Advice',
	components: { HyForm,Upload },
	props: {
		dialogFormVisible: {
			type: Boolean,
			default: true,
		},
		appCode:{
			type:String,
			default:''
		},
		processInstanceId:{
			type:String,
			default:''
		},
		nodeId:{
			type:String,
			default:''
		},
		taskId:{
			type:String,
			default:''
		},
		pageType:{
			type:Number,
			default:3
		}
	},
	setup(props,{ emit }) {
		interface ParamMap {
			[key:string]:boolean|string
		}
		const hyFormConfig = computed(() => {
      return {
        span: 24,
        offset: 0,
        labelWidth: '80px',
        type: 'submit',
      }
    });
    const hyFormFields = ref({
      result: {
        type: 'select',
        label: '审核结果',
        required: true,
				remove:props.pageType==3?true:false,
        options: [
          {
            label: '通过',
            value: '1',
          },
          {
            label: '未通过',
            value: '2',
          },
        ],
      },
			auditAuth: {
        type: 'select',
        label: '审核结果',
        required: true,
				remove:props.pageType==3?false:true,
        options: [
          {
            label: '通过',
            value: '1',
          },
          {
            label: '未通过',
            value: '2',
          },
        ],
      },
      opinion: {
        required: true,
        type: 'textarea',
        label: '审批意见',
      }
    });
    const hyFormDefault = ref({
      result:'',
      auditAuth:'',
      opinion: '',
    });

    const fileList = ref<UploadUserFile[]>([])
		const hyFormRef = ref<any>(null);
		const loading = ref(false);

		function confirm() {
			console.log(hyFormRef.value.hyForm)
			hyFormRef.value.check().then((valid:boolean)=>{
				if(valid){
					let arr:Array<Object> = []
					fileList.value.forEach((item) => {
						if (item.response && item.response.ok) {
							let json = {
								name: item.name||item.response.data?.name,
								url: item.response.data?.url,
							};
							arr.push(json);
						}
					});
					let paramMap:ParamMap = {
						appCode:props.appCode
					}
					if(props.pageType==3){
						paramMap['auditAuth'] = hyFormRef.value.hyForm.auditAuth==1?true:false
						paramMap['pass'] = true
						paramMap['operation'] = hyFormRef.value.hyForm.auditAuth==1?'pass':'reject'
						paramMap[props.nodeId+'_approve_condition'] = hyFormRef.value.hyForm.auditAuth==1?true:false
					}else{
						paramMap['pass'] = hyFormRef.value.hyForm.result==1?true:false
						paramMap['operation'] = hyFormRef.value.hyForm.result==1?'pass':'reject'
						paramMap[props.nodeId+'_approve_condition'] = hyFormRef.value.hyForm.result==1?true:false
					}
					
					let params = {
						processInstanceId:props.processInstanceId,
            nodeId:props.nodeId,
            taskId:props.taskId,
						paramMap,
						taskLocalParamMap: {
							approveDesc: hyFormRef.value.hyForm.opinion,
							fileUrl:arr
						},
					}
					console.log(params)
					loading.value = true
					appDeclareApprove(params).then(res=>{
						if(res.ok){
							ElMessage.success('操作成功')
							handleCancel(1)
						}else{
							ElMessage.error(res.msg)
						}
					}).finally(()=>{
						loading.value = false
					})
				}
			})
		}
    function handleCancel(flag:string|number){
			hyFormRef.value.resetFields()
      emit('handleCancel',flag)
    }
		const headers = computed(() => {
			return {
				Authorization: 'Bearer ' + Session.get('token'),
				'TENANT-ID': Session.getTenant(),
			};
		});
    const accept = ref('.doc,.docx,.pdf,.jpg,.jpeg,.png')
		function beforeUpload(file:File) {
			const { size, type } = file;
			const fileType = accept.value.split(',')
			// const fileType = []
			if (fileType.length) {
				const fileName = file.name.split('.');
				const fileExt = `.${fileName[fileName.length - 1]}`;
				const isTypeOk = fileType.includes(fileExt);
				if (!isTypeOk) {
					ElMessage.error(`文件格式错误，请上传 ${fileType.join(',')} 格式的文件`);
					return false;
				}
			}
			const maxSize = 1024 * 1024 * 200; // 例如，限制为 200MB
			if (size > maxSize) {
				ElMessage.error('文件大小超过限制，请选择小于 200MB 的文件');
				return false;
			}
			return true;
		}
		function handleExceed(files:FileList,uploadFiles:UploadFiles,limit:number|string){
			ElMessage.warning(`最多上传${limit}个文件!`)
		}
		return {
			hyFormConfig,
			hyFormFields,
			hyFormDefault,
      fileList,
			hyFormRef,
      headers,
			accept,
			loading,
			handleExceed,
			confirm,
      handleCancel,
      beforeUpload,
		};
	},
});
</script>
